//
//  PayViewController.m
//  PigMarket
//
//  Created by mac on 2019/4/9.
//  Copyright © 2019 felix.pigmarket.oc. All rights reserved.
//

#import "PayViewController.h"
#import "PayResultViewController.h"
#import "PigPayFooterView.h"
#import "PayCell.h"
#import "PayHeaderView.h"
#import <AlipaySDK/AlipaySDK.h>
#import "PayTypeMenu.h"

@interface PayViewController ()<UITableViewDelegate,UITableViewDataSource,WXApiDelegate>
/**
 currentScene
 */
@property (nonatomic) enum WXScene currentScene;
/**
 tableView
 */
@property (nonatomic , strong) UITableView *myTableView;
/**
 header
 */
@property (nonatomic , strong) PayHeaderView *headerView;
/**
 footer
 */
@property (nonatomic , strong) PigPayFooterView *footerView;
/**
 dateArr
 */
@property (nonatomic , strong) NSMutableArray *dateArr;
/**
 yve
 */
@property (nonatomic , assign) NSNumber *balance;
/**
 wxPay
 */
@property (nonatomic , strong) NSString *wechatPaySelectStatus;
/**
 zfbPay
 */
@property (nonatomic , strong) NSString *aliplayPaySelectStatus;
/**
 yePay
 */
@property (nonatomic , strong) NSString *balancePaySelectStatus;
/**
 选择充值方式
 */
@property (nonatomic , strong) PayTypeMenu *payTypeMenu;
/**
 充值金额
 */
@property (nonatomic , strong) NSString *topUpMoney;
@end

@implementation PayViewController

@synthesize currentScene = _currentScene;

#pragma mark - view life cycle
- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"支付";
    [self setUpView];
}

-(void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    //获取余额请求
    [self balanceRequest];
}

-(void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];
}
- (void)viewWillDisappear:(BOOL)animated {
    if (self.payTypeMenu) {
        [self.payTypeMenu removeFromSuperview];
    }
}
#pragma mark - init method
- (void)setUpView {
    [self initView];
    [self initLayout];
    [self initAction];
    [self initData];
}
- (void)initView {
    [self.view addSubview:self.headerView];
    [self.view addSubview:self.myTableView];
    [self.view addSubview:self.footerView];
}

- (void) initLayout {
    [self.headerView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(10);
        make.left.right.mas_equalTo(0);
    }];
    [self.footerView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.mas_equalTo(0);
        make.bottom.mas_equalTo(-20);
    }];

    [self.myTableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.headerView.mas_bottom);
        make.left.mas_equalTo(0);
        make.right.mas_equalTo(0);
        make.bottom.mas_equalTo(self.footerView.mas_bottom);
    }];
}

- (void) initAction {
    [self.footerView.confirmBtn addTarget:self action:@selector(payTapped) forControlEvents:UIControlEventTouchUpInside];
    
    
}

- (void)initData {
    
    //默认选中微信支付
    self.wechatPaySelectStatus = @"YES";
    [self refreshData];
    [self.headerView.headerImgView sd_setImageWithURL:[NSURL URLWithString:self.model.headImg] placeholderImage:[UIImage imageNamed:@"placeholder_small"]];
    self.headerView.varietyLab.text = self.model.varietiesName;
    self.headerView.numLab.text = [NSString stringWithFormat:@"编号%@",self.model.pigNum];
    self.headerView.priceLab.text = [NSString stringWithFormat:@"￥%@",self.actuallyPaymentMoney];
    self.footerView.priceLab.text = [NSString stringWithFormat:@"￥%@",self.actuallyPaymentMoney];
    self.footerView.discountsLab.text = nil;
}
- (void)refreshData {
    [self.dateArr removeAllObjects];
    NSString *balance = [NSString stringWithFormat:@"可用余额:%@",self.balance];
    NSString *wxStatus = self.wechatPaySelectStatus ? self.wechatPaySelectStatus : @"NO";
    NSString *alipayStatus = self.aliplayPaySelectStatus ? self.aliplayPaySelectStatus : @"NO";
    NSString *balanceStatus = self.balancePaySelectStatus ? self.balancePaySelectStatus : @"NO";
    NSArray *arr = @[@[@{@"icon":@"",@"title":@"第三方支付方式",@"rightBtn":@"",@"isSelect":@"NO"},
                       @{@"icon":@"pay_weichat",@"title":@"微信支付",@"rightBtn":@"selectBtn",@"isSelect":wxStatus},
                       @{@"icon":@"pay_alipay",@"title":@"支付宝",@"rightBtn":@"selectBtn",@"isSelect":alipayStatus}],
                     @[@{@"icon":@"",@"title":@"账户支付",@"rightBtn":@"",@"isSelect":@"NO"},
                       @{@"icon":@"pay_remainingsum",@"title":@"余额支付",@"rightBtn":@"selectBtn",@"isSelect":balanceStatus},
                       @{@"icon":@"",@"title":@"￥",@"rightBtn":@"topUp",@"isSelect":@"NO"},
                       @{@"icon":@"",@"title":balance,@"rightBtn":@"",@"isSelect":@"NO"}]];
    
    NSString *discountMoney = [NSString stringWithFormat:@"(已优惠%@元)",self.discountMoney ? self.discountMoney : @"0"];
    self.footerView.infoDic = @{@"title":@"实付款",
                                @"discount":discountMoney,
                                @"confirmTitle":@"立即支付"
                                };
    [self.dateArr addObjectsFromArray:arr];

}
#pragma mark - delegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 2;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (section == 0) {
        return 3;
    }else {
        return 4;
    }
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 10;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 0.01;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    return [[UIView alloc] init];
}
-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    return [[UIView alloc] init];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    PayCell *cell = [PayCell cellWithTableView:tableView];
    cell.infoDic = self.dateArr[indexPath.section][indexPath.row];
    @weakify(self);
    UITextField *moneyField = cell.textField;
    [cell setTopUpBlock:^{//充值
        self.topUpMoney = moneyField.text;
        @strongify(self);
        [self topUp];
    }];
    return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    
    if (indexPath.section == 0) {
        switch (indexPath.row) {
            case 1:
#warning 待优化
                self.wechatPaySelectStatus = @"YES";
                self.aliplayPaySelectStatus = @"NO";
                self.balancePaySelectStatus = @"NO";
                break;
            case 2:
                self.wechatPaySelectStatus = @"NO";
                self.aliplayPaySelectStatus = @"YES";
                self.balancePaySelectStatus = @"NO";
                break;
            default:
                break;
        }
    } else {
        switch (indexPath.row) {
            case 1:
                self.wechatPaySelectStatus = @"NO";
                self.aliplayPaySelectStatus = @"NO";
                self.balancePaySelectStatus = @"YES";
                break;
            case 2:
                
                break;
            default:
                break;
        }
    }
    [self refreshData];
    [self.myTableView reloadData];
}
#pragma mark - target action
- (void)payTapped {
  
    if ([self.wechatPaySelectStatus boolValue]) {
        //微信支付
        [self payRequestWithPayPassword:@"" withPayType:@3];
    } else if ([self.aliplayPaySelectStatus boolValue]) {

        //支付宝
        [self payRequestWithPayPassword:@"" withPayType:@2];
    } else if ([self.balancePaySelectStatus boolValue]) {
        //支付密页面
        @weakify(self);
        [[PayInputView sharedInstance] display];
        [[PayInputView sharedInstance] setInputCompleteBlock:^(SecureTextEntryView * _Nonnull secureView) {
            @strongify(self);
            [self payRequestWithPayPassword:secureView.text withPayType:@1];
        }];
    } else {
        return;
    }
}
#pragma mark - private method
#pragma mark - 支付
//支付
- (void)payRequestWithPayPassword:(NSString *)password withPayType:(NSNumber *)payType{
    NSNumber *tribeId = [UserInfoDataProvider sharedInstance].userInfo.tribeId;
    NSNumber *pigId = [UserInfoDataProvider sharedInstance].userInfo.pigId;
    NSNumber *memberId = [UserInfoDataProvider sharedInstance].userInfo.memberId;
    NSMutableArray *trusteeIdArr = [[NSMutableArray alloc] init];
    
    //所选套餐的id数组
    NSString *trusteeType = @"1";//默认阶段
    for (AdoptDetail *model in self.model.stagePrices) {
        if (model.isSelect) {
            if ([model.type intValue]== 2) {//总包
                trusteeType = @"2";
            }else if ([model.type intValue]== 1){//阶段
                [trusteeIdArr addObject:model.trustDetailId];
            }
        }
    }
    PayParam *param = [[PayParam alloc] init];
    param.adoptType = @(self.adoptType);
    param.tribeId = tribeId;
    param.pigId = pigId;
    param.payableMoney = self.owedPaymentMoney;
    param.memberId = memberId;
    param.adoptMoney = self.actuallyPaymentMoney;
    param.payType = payType;
    param.trustDetailIds = trusteeIdArr;
    param.type = trusteeType;
    param.payPwd = password;
    param.pigCouponIds = self.discountMoneyIdArr;
    @weakify(self);
    [[[PigMarketApi sharedInstance] payWithParam:param] subscribeNext:^(Pay * _Nullable pay) {
        @strongify(self);
        if ([payType intValue] == 1) {//余额
            
            [[PayInputView sharedInstance] unDisplay];
            [self pushPayResultVCWithModel:pay];
        } else if ([payType intValue] == 2 ) {// 支付宝
            [self alipayWithPayModel:pay memberId:memberId pigId:pigId];

          
        } else if ([payType intValue] == 3) {//微信
            //调取sdk支付
            [self wxPayWithPayModel:pay memberId:memberId pigId:pigId];
        }
    } error:^(NSError * _Nullable error) {
        @strongify(self);
        [self handlingError:error];
        [[PayInputView sharedInstance] unDisplay];
    }];
    
}

//调取微信支付SDK
- (void)wxPayWithPayModel:(Pay *)payModel memberId:(NSNumber *)memberId pigId:(NSNumber *)pigId{
    
    //调取微信支付SDK
    @weakify(self);
    [[PayManager sharedManager] payWithWeChatMethod:payModel callBack:^(PayErrCode errCode, NSString *errStr) {
        @strongify(self);
        if (errCode == PayErrCodeSuccess) {//
            //跳支付成功页面
            [self pushPayResultVCWithModel:payModel];
            
        } else {
            [self toastWithContent:errStr];
        }
    }];
}
//调取支付宝支付SDK
- (void)alipayWithPayModel:(Pay *)payModel memberId:(NSNumber *)memberId pigId:(NSNumber *)pigId{
    //调取支付宝支付SDK
    NSString *orderStr = payModel.payRequest;
    @weakify(self);
    [[PayManager sharedManager] payWithAlipayMethod:orderStr callBack:^(PayErrCode errCode, NSString *errStr) {
        if (errCode == PayErrCodeSuccess) {
            @strongify(self);
            //跳支付成功页面
            [self pushPayResultVCWithModel:payModel];

        } else {
            @strongify(self);
            [self toastWithContent:errStr];
        }
    }];
}

#pragma mark - 充值
//充值
- (void)topUp{
    if (self.topUpMoney.length == 0 || [self.topUpMoney rangeOfString:@"."].location != NSNotFound) {
        [self toastWithContent:@"请输入整数倍金额"];
        return;
    }
    self.payTypeMenu.frame = CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT);
    [[UIApplication sharedApplication].keyWindow addSubview:self.payTypeMenu];
    
    @weakify(self);
    [self.payTypeMenu setSelectPayTypeBlock:^(PayType payType) {
        @strongify(self);
        [self topUpRequestWithPayType:payType];
    }];
}
- (void)topUpRequestWithPayType:(PayType)payType{
    NSNumber *pigId = [UserInfoDataProvider sharedInstance].userInfo.pigId;
    NSNumber *memberId = [UserInfoDataProvider sharedInstance].userInfo.memberId;
    TopUpMoneyParam *param = [[TopUpMoneyParam alloc] init];
    param.payType = @(payType);
    param.pigId = pigId;
    param.memberId = memberId;
    param.money = self.topUpMoney;
    @weakify(self);
    [[[PigMarketApi sharedInstance] topUpRequestWithParam:param] subscribeNext:^(Pay * _Nullable pay) {
        
        @strongify(self);
        switch (payType) {
            case PayTypeWechat:
            {
                //调取微信SDK
                [self thirdTopUpWithPayModel:pay];

            }
                break;
            case PayTypeAlipay:
            {
                //调取支付宝SDK
                [self alipayTopUpWithModel:pay];
            }
                break;
            default:
                break;
        }
     } error:^(NSError * _Nullable error) {
        @strongify(self);
        [self handlingError:error];
    }];
}

//调取微信SDK
- (void)thirdTopUpWithPayModel:(Pay *)payModel{
    
    //调取微信支付SDK
    @weakify(self);
    [[PayManager sharedManager] payWithWeChatMethod:payModel callBack:^(PayErrCode errCode, NSString *errStr) {
        @strongify(self);
        if (errCode == PayErrCodeSuccess) {//成功 调取本地接口
            [self toastWithContent:@"充值成功"];
            //刷新余额
            [self balanceRequest];
            
        } else {
            [self toastWithContent:errStr];
        }
    }];
}
//支付宝充值
- (void)alipayTopUpWithModel:(Pay *)model {
    //调取支付宝支付SDK
    @weakify(self);
    [[PayManager sharedManager] payWithAlipayMethod:model.orderNum callBack:^(PayErrCode errCode, NSString *errStr) {
        if (errCode == PayErrCodeSuccess) {
            @strongify(self);
            [self toastWithContent:@"充值成功"];
            //刷新余额
            [self balanceRequest];
            
        } else {
            @strongify(self);
            [self toastWithContent:errStr];
        }
    }];
}

#pragma mark - 获取余额
//获取余额
- (void)balanceRequest {
    NSNumber *memberId = [UserInfoDataProvider sharedInstance].userInfo.memberId;
    @weakify(self);
    
    [[[PigMarketApi sharedInstance] getBalanceWithMemberId:memberId] subscribeNext:^(Pay * _Nullable pay) {
        @strongify(self);
        self.balance = pay.balance;
        [self refreshData];
        [self.myTableView reloadData];
    } error:^(NSError * _Nullable error) {
        @strongify(self);
        [self handlingError:error];
    }];
}
#pragma mark - 跳到支付成功页面
- (void)pushPayResultVCWithModel:(Pay *)model {
    PayResultViewController *resultVC = [[PayResultViewController alloc] init];
    resultVC.model = model;
    resultVC.actuallyPaymentMoney = self.actuallyPaymentMoney;
    [self.navigationController pushViewController:resultVC animated:YES];
}
#pragma mark - getter and setter
- (UITableView *)myTableView {
    if (!_myTableView) {
        _myTableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStyleGrouped];
        _myTableView.backgroundColor = [UIColor globalBackgroundColor];
        _myTableView.scrollEnabled = NO;
        _myTableView.rowHeight = 54;
        _myTableView.delegate = self;
        _myTableView.dataSource = self;
    }
    return _myTableView;
}
- (PigPayFooterView *)footerView {
    if (!_footerView) {
        _footerView = [[PigPayFooterView alloc] init];
        _footerView.backgroundColor = [UIColor whiteColor];
    }
    return _footerView;
}
- (NSMutableArray *)dateArr {
    if (!_dateArr) {
        _dateArr = [[NSMutableArray alloc] init];
    }
    return _dateArr;
}
- (PayHeaderView *)headerView {
    if (!_headerView) {
        _headerView = [[PayHeaderView alloc] init];
        _headerView.backgroundColor = [UIColor whiteColor];
    }
    return _headerView;
}
- (PayTypeMenu *)payTypeMenu {
    if (!_payTypeMenu) {
        _payTypeMenu = [[PayTypeMenu alloc] init];
    }
    return _payTypeMenu;
}
@end
